package cn.com.dashihui.seller.controller;

import java.util.List;

import com.jfinal.aop.Duang;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.com.dashihui.seller.common.OrderCode;
import cn.com.dashihui.seller.common.SellerState;
import cn.com.dashihui.seller.common.SellerState.DispatchState;
import cn.com.dashihui.seller.dao.Order;
import cn.com.dashihui.seller.kit.DoubleKit;
import cn.com.dashihui.seller.service.OrderService;

public class OrderController extends BaseController{
	//使用Duang.duang进行封装，使普通类具有事务的功能
	private OrderService service = Duang.duang(OrderService.class);
	
	public void index(){
		setAttr("type",getParaToInt("type",0));
		render("index.jsp");
	}
	
	/**
	 * 查询订单列表
	 * @param pageNum 页码
	 * @param pageSize 数量
	 * @param type 订单类型，0：新订单，1：未完成，2：已完成
	 */
	public void page(){
		int pageNum = getParaToInt("pageNum",1);
		int pageSize = getParaToInt("pageSize",PropKit.getInt("constants.pageSize"));
		int type = getParaToInt("type",0);
		if(type==0){
			//查询最新的未接单的订单列表
			List<Order> list = service.findNews(getCurrentStoreid());
			service.getOrderGoodsList(list);
			renderSuccess(list);
		}else{
			//查询其他状态的订单列表
			Page<Order> page = service.findByPage(getCurrentStoreid(),getCurrentSellerid(),type,pageNum,pageSize);
			service.getOrderGoodsList(page.getList());
			renderSuccess(page);
		}
	}
	
	/**
	 * 接单
	 * @param ORDERNUM 订单号
	 */
	public void doAccept(){
		String orderNum = getPara("orderNum");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentStoreid(),orderNum);
			if(order!=null){
				int orderState = order.getInt("orderState");
				//1.判断当前订单是否取消状态
				if(orderState==OrderCode.OrderState.CANCEL){
					//修改订单状态为“已取消”
					order.set("orderState", OrderCode.OrderState.CANCEL);
					//查询订单的商品列表供页面展示
					order.put("goodsList", service.getGoodsListByOrderNum(order.getStr("orderNum")));
					renderResult(1,"当前不允许操作",order);
					return;
				}
				//2.判断订单状态是否为“正常”状态
				if(orderState!=OrderCode.OrderState.NORMAL){
					renderFailed("当前不允许操作");
					return;
				}
				//3.根据订单不同状态进行不同操作
				int payType = order.getInt("payType");
				int payState = order.getInt("payState");
				int takeType = order.getInt("takeType");
				int deliverState = order.getInt("deliverState");
				//((在线支付 and 已支付) or 货到付款) and ((送货上门 and 未发货) or 门店自取)，正常
				if(!(((payType==OrderCode.OrderPayType.ON_LINE&&payState==OrderCode.OrderPayState.HAD_PAY)||payType==OrderCode.OrderPayType.ON_DELIVERY)
						&&((takeType==OrderCode.OrderTakeType.DELIVER&&deliverState==OrderCode.OrderDeliverState.NO_DELIVER)||takeType==OrderCode.OrderTakeType.TAKE_SELF))){
					renderFailed("当前不允许操作");
					return;
				}
				//4.配送员接单，并记录日志
				if(service.doAccept(getCurrentSeller(), order)){
					//修改订单派送状态为待配货
					order.put("state", DispatchState.WAIT_PACK);
					//查询订单的商品列表供页面展示
					order.put("goodsList", service.getGoodsListByOrderNum(order.getStr("orderNum")));
					renderSuccess(order);
					return;
				}
				//4.其他情况
				renderFailed("操作失败");
				return;
			}else{
				renderFailed("订单不存在！");
				return;
			}
		}
	}
	
	/**
	 * 配送员隐藏订单<br/>
	 */
	public void doHide() {
		String orderNum = getPara("orderNum");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentStoreid(),orderNum);
			if(order!=null){
				if(service.hideOrder(getCurrentSellerid(),orderNum)){
					renderSuccess();
					return;
				}
			}else{
				renderFailed("订单不存在！");
				return;
			}
		}
		renderFailed("操作失败！");
		return;
	}
	
	/**
	 * 配货
	 * @param ORDERNUM 订单号
	 */
	public void doPack(){
		String orderNum = getPara("orderNum");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentStoreid(),orderNum);
			if(order!=null){
				int orderState = order.getInt("orderState");
				//1.判断当前订单是否取消状态
				if(orderState==OrderCode.OrderState.CANCEL){
					//修改订单状态为“已取消”
					order.set("orderState", OrderCode.OrderState.CANCEL);
					//查询订单的商品列表供页面展示
					order.put("goodsList", service.getGoodsListByOrderNum(order.getStr("orderNum")));
					renderResult(1,"当前不允许操作",order);
					return;
				}
				//2.判断订单状态是否为“正常”状态
				if(orderState!=OrderCode.OrderState.NORMAL){
					renderFailed("当前不允许操作");
					return;
				}
				if(service.doPack(getCurrentSeller(), order)){
					//修改订单派送状态为配货中
					order.put("state", DispatchState.PACKING);
					//查询订单的商品列表供页面展示
					order.put("goodsList", service.getGoodsListByOrderNum(order.getStr("orderNum")));
					//查询订单各项退款金额，供页面展示
					service.getOrderRefundAmount(order);
					renderSuccess(order);
					return;
				}
				//其他情况
				renderFailed("操作失败");
				return;
			}else{
				renderFailed("订单不存在！");
				return;
			}
		}
	}
	
	/**
	 * 配货完成
	 * @param ORDERNUM 订单号
	 */
	public void doPackFinish(){
		String orderNum = getPara("orderNum");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentStoreid(),orderNum);
			if(order!=null){
				int orderState = order.getInt("orderState");
				//1.判断当前订单是否取消状态
				if(orderState==OrderCode.OrderState.CANCEL){
					//修改订单状态为“已取消”
					order.set("orderState", OrderCode.OrderState.CANCEL);
					//查询订单的商品列表供页面展示
					order.put("goodsList", service.getGoodsListByOrderNum(order.getStr("orderNum")));
					renderResult(1,"当前不允许操作",order);
					return;
				}
				//2.判断订单状态是否为“正常”状态
				if(orderState!=OrderCode.OrderState.NORMAL){
					renderFailed("当前不允许操作");
					return;
				}
				//3.修改状态为“配货完成”
				if(service.doPackFinish(getCurrentSeller(), order)){
					//修改订单派送状态为配货完成
					order.put("state", DispatchState.PACK_FINISH);
					//4.判断如果订单要求是上门自取，则再修改状态为“等待取货”
					if(order.getInt("takeType")==OrderCode.OrderTakeType.TAKE_SELF&&service.doWait(getCurrentSeller(), order)){
						//修改订单派送状态为等待取货
						order.put("state", DispatchState.WAIT_GET);
					}
					//查询订单的商品列表供页面展示
					order.put("goodsList", service.getGoodsListByOrderNum(order.getStr("orderNum")));
					//查询订单各项退款金额，供页面展示
					service.getOrderRefundAmount(order);
					renderSuccess(order);
					return;
				}
				//其他情况
				renderFailed("操作失败");
				return;
			}else{
				renderFailed("订单不存在！");
				return;
			}
		}
	}
	
	/**
	 * 送货
	 * @param ORDERNUM 订单号
	 */
	public void doSend(){
		String orderNum = getPara("orderNum");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentStoreid(),orderNum);
			if(order!=null){
				int orderState = order.getInt("orderState");
				//1.判断当前订单是否取消状态
				if(orderState==OrderCode.OrderState.CANCEL){
					//修改订单状态为“已取消”
					order.set("orderState", OrderCode.OrderState.CANCEL);
					//查询订单的商品列表供页面展示
					order.put("goodsList", service.getGoodsListByOrderNum(order.getStr("orderNum")));
					renderResult(1,"当前不允许操作",order);
					return;
				}
				//2.判断订单状态是否为“正常”状态
				if(orderState!=OrderCode.OrderState.NORMAL){
					renderFailed("当前不允许操作");
					return;
				}
				if(service.doSend(getCurrentSeller(), order)){
					//修改订单派送状态为配送中
					order.put("state", DispatchState.DISPATCHING);
					//查询订单的商品列表供页面展示
					order.put("goodsList", service.getGoodsListByOrderNum(order.getStr("orderNum")));
					//查询订单各项退款金额，供页面展示
					service.getOrderRefundAmount(order);
					renderSuccess(order);
					return;
				}
				//其他情况
				renderFailed("操作失败");
				return;
			}else{
				renderFailed("订单不存在！");
				return;
			}
		}
	}

	/**
	 * 完成
	 * @param ORDERNUM 订单号
	 */
	public void doFinish(){
		String orderNum = getPara("orderNum");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentStoreid(),orderNum);
			if(order!=null){
				int orderState = order.getInt("orderState");
				//1.判断当前订单是否取消状态
				if(orderState==OrderCode.OrderState.CANCEL){
					//修改订单状态为“已取消”
					order.set("orderState", OrderCode.OrderState.CANCEL);
					//查询订单的商品列表供页面展示
					order.put("goodsList", service.getGoodsListByOrderNum(order.getStr("orderNum")));
					renderResult(1,"当前不允许操作",order);
					return;
				}
				//2.判断订单状态是否为“正常”状态
				if(orderState!=OrderCode.OrderState.NORMAL){
					renderFailed("当前不允许操作");
					return;
				}
				//3.签收订单操作，并记录日志
				try {
					//在service中进行订单签收(修改订单状态、商品返利、用户是否升级为黄金会员)的一系列操作,保证事务回滚
					service.doFinish(getCurrentSeller(),order);
					//修改订单派送状态为完成
					order.put("state", DispatchState.FINISH);
					//查询订单的商品列表供页面展示
					order.put("goodsList", service.getGoodsListByOrderNum(order.getStr("orderNum")));
					//查询订单各项退款金额，供页面展示
					service.getOrderRefundAmount(order);
					renderSuccess(order);
					return;
				} catch (Exception e) {
					e.printStackTrace();
				}
				//其他情况
				renderFailed("操作失败");
				return;
			}else{
				renderFailed("订单不存在！");
				return;
			}
		}
	}
	
	/**
	 * 跳转订单详情页面
	 * @param orderNum 订单号
	 */
	public void detail(){
		setAttr("orderNum", getPara(0));
		render("detail.jsp");
	}
	
	/**
	 * 查询订单详情，及订单商品列表<br/>
	 * @param orderNum 订单号
	 */
	public void getDetail(){
		String orderNum = getPara("orderNum");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentStoreid(),orderNum);
			if(order!=null
					&&(order.getLong("state").intValue()==DispatchState.UNACCEPT
					||(order.getLong("state").intValue()!=DispatchState.UNACCEPT&&order.getInt("isShow")==SellerState.ShowState.SHOW))){
				order.put("goodsList", service.getGoodsListByOrderNum(orderNum));
				//查询订单各项退款金额，供页面展示
				service.getOrderRefundAmount(order);
				renderSuccess(order);
				return;
			}else{
				renderFailed("订单不存在");
				return;
			}
		}
	}
	
	/**
	 * 单个商品退款操作
	 */
	public void refundSingle() {
		String orderNum = getPara("orderNum");
		int orderListid = getParaToInt("orderListid",0);
		if(StrKit.isBlank(orderNum)) {
			renderFailed("参数ORDERNUM不能为空");
    		return;
		} else if(orderListid == 0) {
			renderFailed("参数orderListid不能为空");
			return;
		}  else {
			Order order = service.getOrderByOrderNum(getCurrentStoreid(),getCurrentSellerid(),orderNum);
			if(order!=null){
				int orderState = order.getInt("orderState");
				int payType = order.getInt("payType"), payState = order.getInt("payState");
				//1.判断当前订单是否取消状态
				if(orderState==OrderCode.OrderState.CANCEL){
					//修改订单状态为“已取消”
					order.set("orderState", OrderCode.OrderState.CANCEL);
					//查询订单的商品列表供页面展示
					order.put("goodsList", service.getGoodsListByOrderNum(orderNum));
					renderResult(1,"当前不允许操作",order);
					return;
				}
				//2.判断订单状态是否为“正常”状态
				if(orderState!=OrderCode.OrderState.NORMAL){
					renderFailed("当前不允许操作");
					return;
				}
				//3.判断订单支付方式和支付状态是否为“在线支付+已支付”状态
				if(payType!=OrderCode.OrderPayType.ON_LINE || payState!=OrderCode.OrderPayState.HAD_PAY){
					renderFailed("当前不允许操作");
					return;
				}
				int flag = -1;
				try {
					flag = service.doSingleRefund(orderNum, orderListid, order);
					//退款成功时
					if(flag==2||flag==5){
						order.put("goodsList", service.getGoodsListByOrderNum(orderNum));
						//查询订单各项退款金额，供页面展示
						service.getOrderRefundAmount(order);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				renderResult(flag,order);
				return;
			}
		}
		renderFailed("退款失败");
		return;
	}
	
	/**
	 * 零钱退款操作
	 */
	public void refundChange() {
		String orderNum = getPara("orderNum");
		String changeStr = getPara("change");
		if(StrKit.isBlank(orderNum)) {
			renderFailed("参数orderNum不能为空");
    		return;
		}else if(StrKit.isBlank(changeStr)){
			renderFailed("参数change不能为空");
			return;
		}
		double change = Double.parseDouble(changeStr);
		if(change <= 0) {
			renderFailed("参数change不正确");
			return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentStoreid(),getCurrentSellerid(),orderNum);
			if(order!=null){
				int orderState = order.getInt("orderState");
				int payType = order.getInt("payType"), payState = order.getInt("payState");
				//1.判断当前订单是否取消状态
				if(orderState==OrderCode.OrderState.CANCEL){
					//修改订单状态为“已取消”
					order.set("orderState", OrderCode.OrderState.CANCEL);
					//查询订单的商品列表供页面展示
					order.put("goodsList", service.getGoodsListByOrderNum(orderNum));
					renderResult(1,"当前不允许操作",order);
					return;
				}
				//2.判断订单状态是否为“正常”状态
				if(orderState!=OrderCode.OrderState.NORMAL){
					renderFailed("当前不允许操作");
					return;
				}
				//3.判断订单支付方式和支付状态是否为“在线支付+已支付”状态
				if(payType!=OrderCode.OrderPayType.ON_LINE || payState!=OrderCode.OrderPayState.HAD_PAY){
					renderFailed("当前不允许操作");
					return;
				}
				int flag = -1;
				try {
					flag = service.doChangeRefund(change, orderNum, order);
					//退款成功时
					if(flag==2||flag==4){
						order.put("goodsList", service.getGoodsListByOrderNum(orderNum));
						//查询订单各项退款金额，供页面展示
						service.getOrderRefundAmount(order);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				renderResult(flag,order);
				return;
			}
		}
	}
	
	/**
	 * 获取可退款金额
	 */
	public void getAvailable() {
		String orderNum = getPara("orderNum");
		if(StrKit.isBlank(orderNum)) {
			renderFailed("参数ORDERNUM不能为空");
			return;
		}
		double available = 0;
		Order order = service.getOrderByOrderNum(getCurrentStoreid(),getCurrentSellerid(),orderNum);
		if(order!=null){
			int orderState = order.getInt("orderState");
			//1.判断当前订单是否取消状态||是否是未接单状态
			if(orderState==OrderCode.OrderState.CANCEL){
				//修改订单状态为“已取消”
				order.set("orderState", OrderCode.OrderState.CANCEL);
				//查询订单的商品列表供页面展示
				order.put("goodsList", service.getGoodsListByOrderNum(orderNum));
				renderResult(1,"当前不允许操作",order);
				return;
			}
			//2.判断订单状态是否为“正常”状态
			if(orderState!=OrderCode.OrderState.NORMAL){
				renderFailed("当前不允许操作");
				return;
			}
			Record record = service.getOrderRefundAmount(orderNum);
			if(record == null) {
				renderFailed("未找到该订单");
				return;
			}
			//用订单总金额减去单商品退款金额，再减去零钱退款金额，得出当前可退金额
			available = DoubleKit.sub(DoubleKit.sub(record.getDouble("orderAmount"),record.getDouble("singleRefundAmount")),record.getDouble("changeRefundAmount"));
		}
		renderSuccess(available);
	}
	
	/**
	 * 跳转配货单页面
	 */
	public void packTicket(){
		setAttr("orderNum", getPara(0));
		render("ticket/pack.jsp");
	}
	
	public void deliverTicket(){
		setAttr("orderNum", getPara(0));
		render("ticket/deliver.jsp");
	}
	
	/**
	 * 展示配货单内容
	 */
	public void showPackTicket() {
		String orderNum = getPara("orderNum");
		if(StrKit.isBlank(orderNum)) {
			renderFailed("参数ORDERNUM不能为空");
			return;
		} else {
			Order order = service.getOrderByOrderNum(getCurrentStoreid(),orderNum);
			if(order!=null
					&&(order.getLong("state").intValue()==DispatchState.UNACCEPT
					||(order.getLong("state").intValue()!=DispatchState.UNACCEPT&&order.getInt("isShow")==SellerState.ShowState.SHOW))){
				order.put("goodsList", service.getGoodsListByOrderNum(orderNum));
				renderSuccess(order);
				return;
			}else{
				renderFailed("订单不存在");
				return;
			}
		}
	}
	
	/**
	 * 展示送货单内容
	 */
	public void showDeliverTicket(){
		String orderNum = getPara("orderNum");
		if(StrKit.isBlank(orderNum)) {
			renderFailed("参数ORDERNUM不能为空");
			return;
		} else {
			Order order = service.getOrderByOrderNum(getCurrentStoreid(),orderNum);
			if(order!=null
					&&(order.getLong("state").intValue()==DispatchState.UNACCEPT
					||(order.getLong("state").intValue()!=DispatchState.UNACCEPT&&order.getInt("isShow")==SellerState.ShowState.SHOW))){
				order.put("goodsList", service.getGoodsListByOrderNum(orderNum));
				List<Record> listRefund = service.getRefundListByOrderNum(orderNum);
				//商品退款总金额
				double goodsRefundAmount = 0;
				//零钱退款总金额
				double changeRefundAmount = 0;
				//总退款金额
				double refundAmount = 0;
				//实际支付金额
				double actualPay = 0;
				if(listRefund.size() > 0) {
					for(Record record : listRefund) {
						int type = record.getInt("type");
						if(type==OrderCode.RefundType.CANCEL_SINGLE) {
							goodsRefundAmount = record.getDouble("amount");
						} else if(type==OrderCode.RefundType.CHANGE_REFUND) {
							changeRefundAmount = record.getDouble("amount");
						}
					}
					refundAmount = DoubleKit.add(goodsRefundAmount, changeRefundAmount);
					actualPay = DoubleKit.sub(order.getDouble("amount"), refundAmount);
					order.put("goodsRefundAmount",goodsRefundAmount);
					order.put("changeRefundAmount",changeRefundAmount);
					order.put("actualPay",actualPay);
				} else {
					order.put("refundList",null);
				}
				renderSuccess(order);
				return;
			}else{
				renderFailed("订单不存在");
				return;
			}
		}
	}
}
